#include "SharedObjectPtr.h"
#include "WeakObjectPtr.h"

#include "Object/Object.h"


SObjectReferenceCounter *WH::GetOrCreateObjectReferenceCounter(const RObject *InObject)
{
    SObjectHead *ObjectHead =InObject->GetObjectHead();

    if(ObjectHead->RefCounterPtr)
    {
        return ObjectHead->RefCounterPtr;
    }

    ObjectHead->RefCounterPtr =new SObjectReferenceCounter();
    ObjectHead->RefCounterPtr->ObjectHead =ObjectHead;

    return ObjectHead->RefCounterPtr;
}

WHENGINE_API void WH::DestroyReferenceCounter(SObjectReferenceCounter* InCounter)
{
    auto ObjectHead=InCounter->ObjectHead;
    //set to nullptr,because DestroyObject() maybe cant destroy object immediately because bIsDestroying in object head 
    ObjectHead->RefCounterPtr=nullptr; 

    WH::DestroyObject(ObjectHead->GetThisObject());
    delete InCounter;    
}

SObjectWeakReferenceCounter *WH::GetOrCreateObjectWeakReferenceCounter(const RObject *InObject)
{
    SObjectHead *ObjectHead =InObject->GetObjectHead();

    if(ObjectHead->WeakRefCounterPtr)
    {
        return ObjectHead->WeakRefCounterPtr;
    }

    ObjectHead->WeakRefCounterPtr =new SObjectWeakReferenceCounter();
    ObjectHead->WeakRefCounterPtr->ObjectHead =ObjectHead;

    return ObjectHead->WeakRefCounterPtr;
}

void WH::DeleteObjectWeakReferenceCounter(SObjectWeakReferenceCounter* InWeakRefCounter)
{
    SObjectHead* ObjectHead = InWeakRefCounter->ObjectHead;

    if (!ObjectHead)
    {
        //object is already destroyed
        delete InWeakRefCounter;
        return;
    }


    ObjectHead->WeakRefCounterPtr = nullptr;
    delete InWeakRefCounter;
}